package org.wutopia.examples.elasticsearch;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.transport.TransportUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Configuration
public class ESClientConfig {

    @Value("${elasticsearch.uri}")
    private String serverUrl;

    @Value("${elasticsearch.username}")
    private String login;

    @Value("${elasticsearch.password}")
    private String apiKey;


    @Value("${elasticsearch.ca-path}")
    private String capath;


    @Bean
    public ElasticsearchClient getESClient() throws IOException {

        // URL and API key
//        String serverUrl = "https://localhost:9200";
//        String login = "elastic";
//        String apiKey = "0b5QJV0SIXyA0aomDgh-";

//        File certFile = new File("classpath://http_ca.crt");
        InputStream input = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream(capath);

        SSLContext sslContext = TransportUtils.sslContextFromHttpCaCrt(input);
//        SSLContext sslContext = TransportUtils
//                .sslContextFromHttpCaCrt(certFile);

        ElasticsearchClient esClient = ElasticsearchClient.of(b -> b
                .host(serverUrl)
                .usernameAndPassword(login, apiKey)
                .sslContext(sslContext)
        );
        return esClient;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        // 禁用时间戳格式（否则 LocalDateTime 会序列化为数组 [2025,6,29,14,30]）
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return objectMapper;
    }

}
